<script setup>
import { ref, computed, inject, onBeforeUpdate } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
import { usePlayListStore } from '@/stores'
const playListStore = usePlayListStore()
import { useMusicCell } from '@/composables/musicCell.js'
const musicCell = useMusicCell()
// import { useMusicPlayListStore } from '@/stores'
// const musicPlayListStore = useMusicPlayListStore()
// 歌单索引
const itemIndex = computed(() => route.query.n)
// 歌单列表
const listItem = ref({})
listItem.value = playListStore.getListItem(itemIndex.value)
// listItem.value.list = [
//   {
//     name: '歌名',
//     audio_url:
//       'http://lw.sycdn.kuwo.cn/886eb2d5d23f206a12d68201545a8e8a/66d465dc/resource/30106/trackmedia/M800000IZDO70yZWXT.mp3',
//     singer: '歌手',
//     album: '专辑',
//     cover:
//       'http://p2.music.126.net/34YW1QtKxJ_3YnX9ZzKhzw==/2946691234868155.jpg?param=300x300',
//     rid: '',
//     msg: ''
//   }
// ]
// 编辑弹出层
const showEdit = ref(false)
const editActions = [{ name: '重命名' }, { name: '删除', color: '#ee0a24' }]

const playTitleInputRef = ref()
const onRenamePlay = (title) => {
  listItem.value.title = title
  showEdit.value = false
  showSuccessToast('重命名成功')
}
const onEdit = (item) => {
  // 默认情况下点击选项时不会自动收起
  // 可以通过 close-on-click-action 属性开启自动收起
  if (item.name === '重命名') {
    playTitleInputRef.value.showDialog(listItem.value.title)
  } else {
    // playListStore.delListItem(itemIndex.value)
    showConfirmDialog({
      title: '确定要删除吗？'
    })
      .then(() => {
        // on confirm
        playListStore.delListItem(itemIndex.value)
        showNotify({ type: 'success', message: '删除成功' })
        router.replace('/user')
      })
      .catch(() => {
        // on cancel
      })
  }
  // showEdit.value = false
}

const beforeClose = ({ name, position }) => {
  switch (position) {
    case 'cell':
    case 'left':
    case 'outside':
      return true
    case 'right':
      return new Promise((resolve) => {
        showConfirmDialog({
          title: '确定删除吗？'
        })
          .then(() => {
            // console.log(name)
            listItem.value.list.splice(name, 1)
            showNotify({ type: 'success', message: '删除成功', duration: 1000 })
            resolve(true)
          })
          .catch(() => resolve(false))
      })
  }
}
const musicPlayer = inject('musicPlayerRef')
// 播放全部
const onPlayAll = () => {
  // musicPlayListStore.setMusicPlayList(listItem.value.list)
  musicPlayer.value.setList(listItem.value.list)
}
// import { getKWMusicService, getWYYMusicService } from '@/api/music'
// 添加音乐
const onAddMusic = async (item, isPlay) => {
  // const musicUrl = await getKWMusicService('228908')
  // console.log(musicUrl.data)

  await musicCell.addMusic(item, isPlay)
}
// 收藏
const onAddLike = (item) => {
  musicCell.addLike(item, [0])
}
// 更多
const moreModeRef = ref(null)
const onShowMore = (item) => {
  moreModeRef.value.showMoreMode()
  moreModeRef.value.initInfo({ ...item })
}
// const onDownloadFile = async (item) => {
//   await musicCell.downloadFile(item)
// }
// 批量操作
const showChoices = ref(false)
// const onshowChoices = () => {
//   showChoices.value = !showChoices.value
// }

// 歌单列表
const checkedMusic = ref([]) // 选中的歌单
const checkboxMusicRefs = ref([])
const toggleMusic = (index) => {
  checkboxMusicRefs.value[index].toggle()
}

onBeforeUpdate(() => {
  checkboxMusicRefs.value = []
})
// 多选框组 组件
const checkboxMusicGroup = ref(null)

const isCheckAllMusic = computed(() => {
  return checkedMusic.value.length === listItem.value.list.length
})
// 全选 取消全选
const checkAllMusic = () => {
  checkboxMusicGroup.value.toggleAll(!isCheckAllMusic.value)
}
// 反选
const toggleAllMusic = () => {
  checkboxMusicGroup.value.toggleAll()
}
// 批量删除
const onDel = () => {
  if (checkedMusic.value.length === 0) return
  showConfirmDialog({
    title: '确定删除吗？'
  })
    .then(() => {
      console.log(checkedMusic.value)
      checkedMusic.value.forEach((item) => {
        listItem.value.list.splice(item, 1)
      })
      showNotify({ type: 'success', message: '删除成功', duration: 1000 })
      checkedMusic.value = []
    })
    .catch()
}

const choicesPlayModelRef = ref()
// 批量添加到歌单
const showChoicesAddTo = ref(false)
const actionsAddTo = [{ name: '歌单' }, { name: '播放列表' }]
const onSelectAddTo = (action) => {
  const musicArr = checkedMusic.value.map((item) => listItem.value.list[item])
  if (action.name === '歌单') {
    choicesPlayModelRef.value.onShowPlayModal(musicArr)
    // console.log(musicArr)
  } else if (action.name === '播放列表') {
    musicPlayer.value.insertMusic(musicArr)
  }
}
const onAddTo = () => {
  if (checkedMusic.value.length === 0) return
  showChoicesAddTo.value = true
}
const onClose = () => {
  if (!choicesPlayModelRef.value.isScroll) {
    showChoicesAddTo.value = false
  } else {
    choicesPlayModelRef.value.onShowPlayModal()
  }
}

const noDown = ref([])
// 批量下载
const down = async (n) => {
  if (n <= 0) return
  n--
  await showConfirmDialog({
    title: '下载中',
    confirmButtonText: '去下载',
    message: `${listItem.value.list[checkedMusic.value[n]].singer} - ${listItem.value.list[checkedMusic.value[n]].name}.mp3`
  })
    .then(() => {
      musicCell.downloadFile(listItem.value.list[n])
    })
    .catch(() => {
      noDown.value.push(checkedMusic.value[n])
    })
  await down(n)
}
const onDownload = async () => {
  if (checkedMusic.value.length === 0) return
  await down(checkedMusic.value.length)
  console.log(noDown.value)

  checkedMusic.value = noDown.value
  showDialog({
    title: '下载完成',
    message: '已将未下载的音乐选中'
  }).then(() => {
    // on close
  })
  noDown.value = []
}
</script>

<template>
  <div class="list-page">
    <!-- 歌单标题栏 -->
    <div class="list-header">
      <van-nav-bar
        :fixed="true"
        :placeholder="true"
        :title="listItem.title"
        left-arrow
        @click-left="router.replace('/user')"
      >
        <template #right>
          <van-icon
            v-if="itemIndex !== '0'"
            name="edit"
            size="20px"
            @click="showEdit = true"
          />
          <!-- <van-icon name="ellipsis" size="20px" /> -->
        </template>
      </van-nav-bar>
      <van-action-sheet
        v-model:show="showEdit"
        :actions="editActions"
        cancel-text="取消"
        safe-area-inset-bottom
        @select="onEdit"
      />
      <!-- 重命名歌单弹窗 -->
      <PlayTitleInput
        ref="playTitleInputRef"
        @rename-play="onRenamePlay"
      ></PlayTitleInput>
    </div>
    <!-- 操作栏 -->
    <div class="operate">
      <van-sticky offset-top="46">
        <van-cell
          center
          border
          title-style="display: flex;align-items: center;"
        >
          <!-- 使用 title 插槽来自定义标题 -->
          <template #title>
            <van-button
              round
              type="primary"
              @click="onPlayAll()"
              :disabled="listItem.list.length === 0"
            >
              <van-icon
                size="22px"
                name="play"
                style="margin-left: 2px; margin-right: 2px"
              />
            </van-button>
            <span style="margin-left: 10px">
              全部播放 ({{ listItem.list.length }})
            </span>
          </template>
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #right-icon>
            <van-icon @click="showChoices = true" size="22px" name="bars" />
          </template>
        </van-cell>
      </van-sticky>
    </div>
    <div class="list-content">
      <van-swipe-cell
        v-for="(item, index) in listItem.list"
        :key="index"
        :name="index"
        :stop-propagation="true"
        :before-close="beforeClose"
      >
        <van-cell
          center
          :title="item.name"
          :label="`${item.singer}${item.album ? ' - ' + item.album : ''}`"
          @click="onAddMusic(item, 1)"
        >
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #right-icon>
            <div class="right-icon">
              <!-- 添加 -->
              <i>
                <van-icon
                  class-prefix="my-icon"
                  name="addNext"
                  @click.stop="onAddMusic(item, 0)"
                />
              </i>
              <!-- 收藏 -->
              <i><van-icon @click.stop="onAddLike(item)" name="star-o" /></i>
              <!-- 更多 -->
              <i><van-icon name="ellipsis" @click.stop="onShowMore(item)" /></i>
            </div>
          </template>
        </van-cell>
        <!-- 右侧删除按钮 -->
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            style="right: -1px; height: 100%"
          />
          <!-- @click="onDelPlay(index)" -->
        </template>
      </van-swipe-cell>
    </div>
    <MoreMode ref="moreModeRef"></MoreMode>
    <!-- 批量操作 -->
    <van-popup
      v-model:show="showChoices"
      position="bottom"
      :safe-area-inset-bottom="true"
      :style="{
        height: '100%',
        backgroundColor: 'var(--common-background-color)'
      }"
      z-index="998"
    >
      <van-nav-bar
        :title="
          checkedMusic.length > 0
            ? `已选定 ${checkedMusic.length} 首`
            : '批量操作'
        "
        right-text="完成"
        @click-right="
          () => {
            showChoices = false
            checkedMusic = []
          }
        "
        border
        fixed
        safe-area-inset-top
        placeholder
      >
        <template #left>
          <div>
            <van-button
              type="primary"
              plain
              hairline
              size="mini"
              @click="checkAllMusic"
              style="margin-right: 8px"
            >
              {{ isCheckAllMusic ? '取消全选' : '全选' }}
            </van-button>
            <van-button
              type="primary"
              plain
              hairline
              size="mini"
              @click="toggleAllMusic"
            >
              反选
            </van-button>
          </div>
        </template>
      </van-nav-bar>
      <div class="list">
        <van-checkbox-group v-model="checkedMusic" ref="checkboxMusicGroup">
          <van-cell-group>
            <van-cell
              center
              clickable
              v-for="(item, index) in listItem.list"
              @click="toggleMusic(index)"
              :key="index"
              :title="item.name"
              :label="`${item.singer}${item.album ? ' - ' + item.album : ''}`"
            >
              <template #right-icon>
                <van-checkbox
                  :name="index"
                  :ref="(el) => (checkboxMusicRefs[index] = el)"
                  @click.stop
                />
              </template>
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </div>
      <!-- <div class="list" style="height: 600px">1111111111</div> -->
      <div class="bottom">
        <van-grid
          :column-num="3"
          clickable
          :class="{ disabled: checkedMusic.length === 0 }"
        >
          <van-grid-item @click="onDel()" icon="delete-o" text="删除" />
          <van-grid-item
            @click="onAddTo()"
            icon-prefix="my-icon"
            icon="add"
            text="添加到"
          />
          <van-grid-item
            @click="onDownload()"
            icon-prefix="my-icon"
            icon="download"
            text="下载"
          />
        </van-grid>
      </div>
      <!-- 添加到动作面板 -->
      <van-action-sheet
        v-model:show="showChoicesAddTo"
        :actions="actionsAddTo"
        cancel-text="取消"
        @select="onSelectAddTo"
        :close-on-click-overlay="false"
        @click-overlay="onClose()"
        z-index="998"
      />
      <!-- 歌单模态框 -->
      <PlayModel ref="choicesPlayModelRef"></PlayModel>
    </van-popup>
  </div>
</template>
<style scoped>
::v-deep .van-icon-arrow-left {
  color: var(--van-nav-bar-icon-color);
}
.bottom {
  height: 95px;
}
.van-grid {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
}
::v-deep .disabled .van-grid-item__content--center {
  background-color: var(--common-background-color);
}
</style>
